<?php

/*
 * To change this license header, choose License Headers in Project Properties.
 * To change this template file, choose Tools | Templates
 * and open the template in the editor.
 */

namespace Admin\Controller;

use Admin\Model\OrderModel;
/**
 * @author wangnaixin
 * @todo 订单中心
 * @menu 订单中心
 * @author wangnaixin
 * @menuAuto index
 * @order 410
 * @icon article.png
 */
class OrderController extends AdminController {
    //put your code here
    
    private $orderModel;
    
    function __construct() {
        parent::__construct();
        $this->orderModel = new OrderModel();
    }
    
    
    public function index (){
        
    }
    
    /**
     * @todo 订单列表
     * @menu 订单列表
     * @order 10
     */
    public function orderList(){
        $this->setForm();
        $order_sn = I('order_sn');
		$start_time = I('start_time');
		$end_time = I('end_time');
		$status = I('status');
        $where= [];
        if(!empty($order_sn)){
            $where['order_sn'] = $order_sn;
        }
		if(!empty($status)){
            $where['status'] = $status;
        }
		
		if(!empty($start_time)){
			$where['ctime'] = ['gt',strtotime($start_time)];
			
		}
		if(!empty($end_time)){
			
			$where['ctime'] = ['lt',strtotime($end_time)+86400];
		}
		if(!empty($start_time) && !empty($end_time)){
			
			$where['ctime'] = [['gt',strtotime($start_time)],['lt',strtotime($end_time)+86400]];
			
		}
        $this->assign("data",$this->orderModel->getList($where));
        $this->display();
    }
    
    public function refundOrder(){
		
        $order_id = I('order_id');
        
        $orderInfo = $this->orderModel->getInfo($order_id);
        $refundData = [
            'funCode' => 'CANCEL01',
            'rpid' => $orderInfo['rpid'],
            'reqDate' => Date("Ymd",time()),
            'reqTime' => Date('His',time()),
            'merId'  => 'W2000089',
            'clientIp' => $orderInfo['clientip'],
            'refundId' => 'refundid_'.$orderInfo['id'],
            'refundDate' => Date("Ymd",time()),
            'orderId' => $orderInfo['order_sn'],
            'orderDate' => Date("Ymd",$orderInfo['ctime']),
            'notifyUrl' => C('CY_REFUND_ORDER_NOTIFY'),
            'goodsId' => $orderInfo['goods_id'],
            'goodsNum' => 1,
            'amount' => (int)$orderInfo['integral'],
            'merPriv' => '',
        ];
        
        $refundData['sign'] = $this->getCySign($refundData);
        file_put_contents("CY_REFUND_ORDER_NOTIFY.log",var_export($refundData,true)."\n",FILE_APPEND);
        $this->sendCyData(C('CY_REFUND_ORDER'), json_encode($refundData));
        file_put_contents("CY_REFUND_ORDER_NOTIFY.log","========================\n",FILE_APPEND);
		$this->success("申请退款成功!");
        
    }
	
	public function output(){
		$order_sn = I('order_sn');
		$start_time = I('start_time');
		$end_time = I('end_time');
		$status = I('status');
        $where= [];
        if(!empty($order_sn)){
            $where['order_sn'] = $order_sn;
        }
		if(!empty($status)){
            $where['status'] = $status;
        }
		
		if(!empty($start_time)){
			$where['ctime'] = ['gt',strtotime($start_time)];
			
		}
		if(!empty($end_time)){
			
			$where['ctime'] = ['lt',strtotime($end_time)+86400];
		}
		if(!empty($start_time) && !empty($end_time)){
			
			$where['ctime'] = [['gt',strtotime($start_time)],['lt',strtotime($end_time)+86400]];
			
		}
        $list = $this->orderModel->getList($where,0,false);
		
		
		
		
		$header_data = array(
            '订单号','商品名称','价格','支付方式','时间', '状态'
        );
        
        
        
        $data = array();
        foreach ($list['data'] as $v) {
            $data[] = array(
                $v['order_sn'],
                $v['goods_name'],
                $v['price']."元",
                $v['pay_type'] == 3 ? "畅由积分" : "其他支付",
                Date("Y-m-d H:i:s",$v['ctime']),
                $v['status'] == 2 ? "已支付" : "待支付"
            );
        }
        export_csv($data, $header_data, "order". Date('YmdHis', time()) .".csv");
	}
	
	
	/**
	*
	* @todo 后台确认收货操作
	**/
	public function orderConfirm(){
		return false;
		$orderId = I("order_id");
		
		$orderInfo = $this->orderModel->getInfo($order_id);
		
		$confirmData = [
			'merId'  => 'W2000089',
            'paySeq' => 'CANCEL01',
			'orderId' => $orderInfo['order_sn'],
			'orderDate' => Date("Ymd",$orderInfo['ctime']),
			'orderStatusCode' => 4,
			'orderStatusDesc' => "后台处理订单确认收货",
			'orderStatusUpdateTime' => Date("YmdHis")
        ];
		
		$confirmData['sign'] = $this->getCySign($confirmData);
		
		
        $res = $this->sendCyData(C(''), json_encode($refundData));
		
		//更改订单状态
		if($res['retCode'] == '0000'){
			
			$this->order->changeStatus($orderId,['status'=>200]);
			$this->success("后台处理订单确认收货成功!");
			
		}else{
			
			$this->error($res['retMsg']);
		}
		
        
		
		
	}
    
    
    private function getCySign($data){
        ksort($data);
        $data['key'] = C('CY_KEY');
        $string = $this->toUrlParams($data);
		file_put_contents("CY_REFUND_ORDER_NOTIFY.log","$string\n",FILE_APPEND);
        return md5($string);
    }
    
    private  function toUrlParams($data){
        $buff = "";
        foreach ($data as $k => $v){
            if($k != "sign"  && !is_array($v)){
                $buff .= $k . "=" . $v . "&";
            }
        }
        $buff = trim($buff, "&");
        return $buff;
    }
    
    private function sendCyData($url,$post){
        $aContext = array('http' => array('method' => 'POST',  
        'header'  => 'Content-type:application/json;charset=utf-8',  
        'content' => $post ));  
        $cxContext  = stream_context_create($aContext);  
        $d = file_get_contents($url,false,$cxContext); 
        return json_decode($d,true);
    }
}
